import comm from './core';

function transformLive (res) {
  const {
    code,
    displayName,
    description,
    address,
    pic,
    poster,
    type,
    liveStatus,
    liveOrderCount,
    videoType,
    stat,
    beginTime,
    guests,
    price,
    contentPackageQueryDtos,
    isChargeable,
    liveMediaDtos
  } = res;

  let mediaDto = {};
  if (liveMediaDtos) {
    for (const item of liveMediaDtos) {
      if (item.source === 'vr_share' && item.status === 1 && (item.renderType.length === 0 || item.renderType.trim() === '360_2D')) {
        mediaDto = item;
        break;
      }
    }
  }
  let itemPrice = (price / 100).toFixed(2);
  if (contentPackageQueryDtos) {
    itemPrice = (contentPackageQueryDtos[0].price / 100).toFixed(2);
  }

  return {
    code: code,
    title: displayName,
    bigImage: comm.formatZoomPic(pic) || comm.formatZoomPic(poster),
    poster: comm.formatZoomPic(poster),
    intro: description,
    address,
    type,
    liveStatus,
    liveOrderCount,
    videoType,
    playCount: comm.dealNumber(stat.playCount),
    startTime: comm.formatDate(new Date(beginTime)),
    startTimestamp: beginTime,
    guests,
    price: itemPrice,
    contentPackageQueryDtos: contentPackageQueryDtos ? contentPackageQueryDtos[0] : null,
    isChargeable: !!isChargeable,
    videoPath: mediaDto ? mediaDto.playUrl : ''
  };
}

function get () {
  const params = comm.requestParams();
  const {
    origin,
    code,
    status
  } = params;
  if (!status || status !== 1) {
    return {};
  }

  const path = `liveProgram/findByCode`;
  const query = `code=${code}`;
  return comm.request({ origin, path, query }).then(({ data }) => {
    if (data) {
      return transformLive(data) || {};
    }
  });
}

function liveBarrage (sid) {
  const query = 'refreshTimestamp=400';
  return comm.json('http://vrtest-api.aginomoto.com', `comment/live/${sid}`, query).then(({ data }) => {
    if (data) {
      return data.comment_data;
    }
    return [];
  });
}
export default {
  get,
  liveBarrage
};
